package cn.sunxyz.modules.memory;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 记忆节点
 * Created by yangrd on 2017/5/11.
 */
public class Node<V> {

    private V value;

    private Set<Node<V>> nodes;

    public Node(V value) {
        this.value = value;
    }

    public V getValue() {
        return value;
    }

    public Set<Node<V>> getNodes() {
        return nodes;
    }

    public Node addNode(Node<V> node) {
        initNodesNotEmepty();
        this.nodes.add(node);
        return this;
    }

    public Node addNodes(Collection<Node<V>> nodes) {
        initNodesNotEmepty();
        this.nodes.addAll(nodes);
        return this;
    }

    protected void clear() {
        this.value = null;
        this.nodes = null;
    }

    public boolean isOtherNode() {
        return this.nodes != null;
    }

    private void initNodesNotEmepty() {
        if (this.nodes == null) {
            synchronized (this) {
                if (this.nodes == null) {
                    this.nodes = new HashSet<>();
                }
            }
        }
    }

    @Override
    public String toString() {
        return value.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Node<?> node = (Node<?>) o;

        return value != null ? value.equals(node.value) : node.value == null;
    }

    @Override
    public int hashCode() {
        return value != null ? value.hashCode() : 0;
    }
}
